import { asyncRoutes, constantRoutes } from '@/router'
import setBaseRouter from '@/router/modules/album/setBase'
import { deepClone } from "@/utils"

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
let isBase = null
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    let tmp = { ...route }
    if (hasPermission([roles], tmp)) {
      if (!isBase) {
        if (!tmp.hidden) {
          isBase = { ...setBaseRouter, redirect: tmp.path }
          res.push(isBase)
        }
      }
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, [roles])
      }
      res.push(tmp)
    }
  })

  return res
}

const getDefaultState = () => {
  return {
    routes: [],
  }
}

const state = getDefaultState()
const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_ROUTES: (state, routes) => {
    state.routes = routes
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes = deepClone(asyncRoutes) || []
      if ([1, 2].includes(roles)) {
        accessedRoutes = [{ ...setBaseRouter }, ...(accessedRoutes || [])]
      } else {
        isBase = null
        accessedRoutes = filterAsyncRoutes(accessedRoutes, roles)
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
